package team.bluepen.supermarket.service;

import org.springframework.stereotype.Service;
import team.bluepen.supermarket.conf.KafkaProperties;
import team.bluepen.supermarket.data.entity.ProductStatusAmount;
import team.bluepen.supermarket.kafka.KafkaReceiveCallback;
import team.bluepen.supermarket.kafka.KafkaReceiver;
import team.bluepen.supermarket.kafka.KafkaTopics;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author RollW
 */
@Service
public class ProductStatusRecvService implements KafkaReceiveCallback<ProductStatusAmount> {
    private final Map<Boolean, ProductStatusAmount> amountMap = new HashMap<>();

    private final KafkaReceiver<ProductStatusAmount> statusAmountReceiver;

    public ProductStatusRecvService(KafkaProperties kafkaProperties) {
        statusAmountReceiver = new KafkaReceiver<>(
                KafkaTopics.STATE_DATA_TOPIC,
                kafkaProperties.getBootstrapServers(),
                "ProductStatusRecvServ",
                DataKeys.PRODUCT_COUNT,
                ProductStatusAmount.deserializer(),
                this);
        statusAmountReceiver.start();
    }

    public Collection<ProductStatusAmount> getStatusAmount() {
        return amountMap.values();
    }

    @Override
    public void onReceive(ProductStatusAmount data) {
        amountMap.put(data.isState(), data);
    }
}
